<?php

namespace Hangpu888\Hpadmin\utils\builder;

use Hangpu888\Hpadmin\utils\manager\AuthManager;

/**
 * @title 表格构造器
 * @desc 用于表格的构造生成器
 * @author 楚羽幽 <admin@hangpu.net>
 */
class ListBuilder
{
    // 数据
    private $data;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->data = [
            'children'              => [
                'api'               => '',
                'method'            => '',
                'field'             => 'id',
            ],
            'screenConfig'          => [
                'api'               => '',
                'method'            => 'get',
                'submitBtn'         => [],
                'params'            => [],
                'rule'              => [],
            ],
            'topButtonList'         => [],
            'rightButtonList'       => [],
            'columns'               => [],
            'dataList'              => [],
            'paginate'              => [
                'total'             => 0,
                'last_page'         => 0,
                'limit'             => 0,
                'page'              => 1
            ],
        ];
    }

    /**
     * 添加筛选参数
     *
     * @param ScreenBuilder $builder
     * @return ListBuilder
     */
    public function addScreen(ScreenBuilder $builder): ListBuilder
    {
        $this->data['screenConfig'] = $builder->create();
        return $this;
    }

    /**
     * 添加表格列
     *
     * @param string $field
     * @param string $title
     * @param array $extra
     * @return $this
     */
    public function addColumn(string $field, string $title, array $extra = [])
    {
        $column = [
            'field'                     => $field,
            'title'                     => $title,
            'extra'                     => [
                'type'                  => '',
                'width'                 => '',
                'height'                => '',
                'show'                  => true,
                'loading'               => false,
                'options'               => [],
            ]
        ];
        $column['extra']            = array_merge($column['extra'], $extra);
        $this->data['columns'][]    = $column;
        return $this;
    }

    /**
     * 设置列表数据
     *
     * @param array $data
     * @return $this
     */
    public function setData(array $data)
    {
        $this->data['dataList'] = $data;
        return $this;
    }

    /**
     * 设置数据分页
     *
     * @param integer $total 数据总数量
     * @param integer $last_page 最后一页
     * @param integer $limit 每页数量
     * @param integer $page 当前分页
     * @return $this
     */
    public function setDataPage(int $total, int $last_page,int $limit = 10, int $page = 1)
    {
        $this->data['paginate'] = [
            'total'             => $total,
            'last_page'         => $last_page,
            'limit'             => $limit,
            'page'              => $page
        ];
        return $this;
    }

    /**
     * 添加顶部按钮
     *
     * @param string $name
     * @param string $title
     * @param array $pageData
     * @param array $style
     * @return $this
     */
    public function addTopButton(string $name, string $title, $pageData = [], $style = [])
    {
        $btn['field']           = $name;
        $btn['title']           = $title;
        $btn['pageData']        = [
            'api'               => '',
            'method'            => 'GET',
            'title'             => '操作窗口',
            'content'           => '',
            'type'              => 'modal', // 支持：page，modal，confirm，table
            'apiPrefix'         => [],
            'width'             => '950px',
            'height'            => '50vh',
        ];
        $pageData               = array_merge($btn['pageData'], $pageData);
        $btn['pageData']        = $pageData;
        // 按钮样式
        $btn['btnStyle']        = array_merge($this->getBtnDefaultStyle(), $style);
        // 按钮显示权限检测(是否开启权限检测)
        if (config('plugin.hangpu888.hpadmin.builder.list.auth')) {
            list($empty, $module, $controller, $action) = explode('/', $pageData['api']);
            $path = "{$controller}/{$action}";
            if (strstr($path, '?')) {
                $pathLength = strpos($path, '?');
                $path = substr($path, 0, $pathLength);
            }
            $auth = new AuthManager((int)request()->user->id, (int)request()->user->role->is_system);
            $btn['btnStyle']['show']   = $auth->check($path);
        }

        $this->data['topButtonList'][] = $btn;
        return $this;
    }

    /**
     * 添加右侧菜单
     *
     * @param string $field
     * @param string $title
     * @param array $pageData
     * @param array $style
     * @return $this
     */
    public function addRightButton(string $field,string $title,array $pageData = [],array $style = [],)
    {
        $btn                    = [];
        $btn['field']           = $field;
        $btn['title']           = $title;
        $btn['pageData']        = [
            'api'                           => '',
            'method'                        => 'GET',
            'title'                         => '操作窗口',
            'content'                       => '',
            'type'                          => 'modal', // 支持：page，modal，confirm，table
            'apiPrefix'                     => [],
            'width'                         => '950px',
            'height'                        => '50vh',
        ];
        $pageData                           = array_merge($btn['pageData'], $pageData);
        $btn['pageData']                    = $pageData;

        // 按钮样式
        $btn['btnStyle']                    = array_merge($this->getBtnDefaultStyle(), $style);
        // 是否开启权限检测
        if (config('plugin.hangpu888.hpadmin.builder.list.auth')) {
            list($empty, $module, $controller, $action) = explode('/', $pageData['api']);
            $path = "{$controller}/{$action}";
            if (strstr($path, '?')) {
                $pathLength = strpos($path, '?');
                $path = substr($path, 0, $pathLength);
            }
            $auth = new AuthManager((int)request()->user->id, (int)request()->user->role->is_system);
            $style['btnStyle']['show']      = $auth->check($path);
        }
        $this->data['rightButtonList'][]    = $btn;
        return $this;
    }

    /**
     * 获得默认按钮样式
     *
     * @param string $type
     * @param string $size
     * @return array
     */
    private function getBtnDefaultStyle(string $type = 'text', string $size = 'small'): array
    {
        $data                   = [
            //类型 default / primary / success / warning / danger / info / text
            'type'              => $type,
            //尺寸 medium / small / mini
            'size'              => $size,
            //是否朴素按钮
            'plain'             => false,
            //是否圆角按钮
            'round'             => false,
            //是否圆形按钮
            'circle'            => false,
            //是否加载中状态
            'loading'           => false,
            //是否禁用状态
            'disabled'          => false,
            //图标类名
            'icon'              => 'el-icon-edit-outline',
            //是否默认聚焦
            'autofocus'         => false,
            //原生 type 属性
            'nativeType'        => "button",
            'show'              => true,
        ];
        return $data;
    }

    /**
     * 设置树列表
     *
     * @param string $api 请求地址
     * @param string $method 请求类型
     * @param string $field 树主键字段
     * @return $this
     */
    public function setChildren(string $api, string $method, string $field)
    {
        $this->data['children']['api'] = $api;
        $this->data['children']['method'] = $method;
        $this->data['children']['field'] = $field;
        return $this;
    }

    /**
     * 构造数据
     *
     * @return array
     */
    public function create(): array
    {
        $tableRule = $this->data;
        return $tableRule;
    }
}
